package com.adingxiong.security.springsecurity.config.sms;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName SmsAuthenticationFilter
 * @Description TODO
 * @Author xiongchao
 * @Date 2020/10/19 11:21
 **/
public class SmsAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private static final String MOBILE_KEY = "mobile";

    private String mobileParameter = MOBILE_KEY;

    private boolean postOnly  = true;

    public SmsAuthenticationFilter(){
        super(new AntPathRequestMatcher("/login/mobile", "POST"));
    }



    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        if(postOnly && !httpServletRequest.getMethod().equals("POST")){
            throw new AuthenticationServiceException("Authentication method not supported:" + httpServletRequest.getMethod());
        }
        String moblie = obtainMobile(httpServletRequest);
        if(moblie == null) {
            moblie = "";
        }
        moblie = moblie.trim();
        SmsAuthenticationToken token = new SmsAuthenticationToken(moblie);
        setDetails(httpServletRequest,token);
        return this.getAuthenticationManager().authenticate(token);
    }

    protected void setDetails(HttpServletRequest httpServletRequest, SmsAuthenticationToken token) {
        token.setDetails(authenticationDetailsSource.buildDetails(httpServletRequest));
    }

    protected String obtainMobile(HttpServletRequest request) {
        return request.getParameter(mobileParameter);
    }

    public void setMobileParameter(String mobileParameter){
        Assert.hasText(mobileParameter,"mobile parameter is not be empty or null");
        this.mobileParameter = mobileParameter;
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getMobileParameter() {
        return mobileParameter;
    }

}
